
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../common/api/index.dart';
import '../../../common/models/index.dart';
import '../../../common/routers/index.dart';
import '../../../common/services/index.dart';
import '../../../common/utils/index.dart';
import '../../../common/values/index.dart';
import '../../apps/AI/view.dart';
import '../../apps/bbs/bbs_subject/index.dart';
import '../../apps/cms/cms_document/index.dart';
import '../../apps/process/process_picker/index.dart';
import '../../common/create_form/index.dart';
import '../../common/portal/index.dart';
import '../../common/process_webview/index.dart';
import '../../common/scan/index.dart';
import 'index.dart';

class DefaultIndexController extends GetxController {
  DefaultIndexController();

  final state = DefaultIndexState();
  final _eventBus = EventBus();
  final _eventId = 'default_index';

  final refreshController = RefreshController();
  int page = 1; // 分页查询
  bool isLoading = false; // 防止重复刷新


  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    OLogger.d('执行拉 onReady');
    _eventBus.on(EventBus.cmsDocumentCloseMsg, _eventId, (arg) {
      refreshDataList();
      OLogger.d('cms 文档 关闭后刷新页面。。。。。');
    });
    _eventBus.on(EventBus.processWorkCloseMsg, _eventId, (arg){
      refreshDataList();
      loadMyAppList();
      OLogger.d('流程工作文档 关闭后刷新页面。。。。。');
    });
    _eventBus.on(EventBus.myAppChangeMsg, _eventId, (arg){
      loadMyAppList();
      OLogger.d('我的应用编辑后刷新列表。。。。。');
    });
    refreshDataList();
    loadHotpicList();
    loadMyAppList();
    checkEnbaleWaterMark();
    super.onReady();
  }

  @override
  void onClose() {
    _eventBus.off(EventBus.cmsDocumentCloseMsg, _eventId);
    _eventBus.off(EventBus.processWorkCloseMsg, _eventId);
    _eventBus.off(EventBus.myAppChangeMsg, _eventId);
    super.onClose();
  }
  /// 下拉刷新
  void onRefresh() {
    loadHotpicList();
    refreshDataList();
  }

  /// 根据分类查询list
  void refreshDataList()  {
    if (state.listType == 0) {
      refreshCmsList();
    } else {
      refreshTaskList();
    }
  }
  void loadMoreData()  {
    if (state.listType == 0) {
      loadMoreCmsList();
    } else {
      loadMoreTaskList();
    }
  }

  /// 待办列表
  Future<void> refreshTaskList() async {
   if (isLoading) return;
    page = 1;
    isLoading = true;
    Map<String, dynamic> data = {
      'processList': ProgramCenterService.to.indexFilterProcessList()
    };
    List<TaskData>? list =
        await ProcessSurfaceService.to.getMyTaskListByPage(page, body: data);
    if (list != null) {
      state.taskList.clear();
      state.taskList.addAll(list);
    }
    refreshController.refreshCompleted();
    state.hasMoreData = (list?.length ?? 0) == O2.o2DefaultPageSize;
    isLoading = false;
  }

  Future<void> loadMoreTaskList() async {
    if (isLoading) return;
    if (!state.hasMoreData) {
      refreshController.loadComplete();
      return;
    }
    isLoading = true;
    page++;
    Map<String, dynamic> data = {
      'processList': ProgramCenterService.to.indexFilterProcessList()
    };
    List<TaskData>? list =
        await ProcessSurfaceService.to.getMyTaskListByPage(page, body: data);
    if (list != null) {
      state.taskList.addAll(list);
    }
    refreshController.loadComplete();
    state.hasMoreData = (list?.length ?? 0) == O2.o2DefaultPageSize;
    isLoading = false;
  }

  /// 信息列表
  Future<void> refreshCmsList() async {
    if (isLoading) return;
    state.hasMoreData = true;
    page = 1;
    isLoading = true;
    Map<String, dynamic> data = {
      'statusList': ['published'],
      'categoryIdList': ProgramCenterService.to.indexFilterCmsCategoryList()
    };
    List<DocumentData>? list =
        await CmsAssembleControlService.to.getCmsDocumentListByPage(page, body: data);
    if (list != null) {
      state.cmsList.clear();
      state.cmsList.addAll(list);
    }
    refreshController.refreshCompleted();
    state.hasMoreData = (list?.length ?? 0) == O2.o2DefaultPageSize;
    isLoading = false;
  }

  Future<void> loadMoreCmsList() async {
    if (isLoading) return;
    if (!state.hasMoreData) {
      refreshController.loadComplete();
      return;
    }
    isLoading = true;
    page++;
    state.hasMoreData = true;
    Map<String, dynamic> data = {
      'statusList': ['published'],
      'categoryIdList': ProgramCenterService.to.indexFilterCmsCategoryList()
    };
    List<DocumentData>? list =
        await CmsAssembleControlService.to.getCmsDocumentListByPage(page, body: data);
    if (list != null) {
      state.cmsList.addAll(list);
    }
    refreshController.loadComplete();
    state.hasMoreData = (list?.length ?? 0) == O2.o2DefaultPageSize;
    isLoading = false;
  }

  /// 热点图片
  Future<void> loadHotpicList() async {
    List<HotpicData>? list =
        await HotpicAssembleControlService.to.findHotPictureList();
    if (list != null) {
      state.hotpicList.clear();
      state.hotpicList.addAll(list);
    }
  }

  /// 我的应用列表
  Future<void> loadMyAppList() async {
    OLogger.i('执行了 loadMyAppList。。。。。。。。。。。。。');
    state.myAppList.clear();
    List<AppFrontData?> newList = [];
    var myApp = await OrganizationPersonalService.to
        .getMyCustomData(O2.myCustomNameMyAppList);
    if (myApp != null && myApp.isNotEmpty) {
      Map<String, dynamic> m = O2Utils.parseStringToJson(myApp);
      List<dynamic>? myAppList = m[O2.myCustomNameMyAppList];
      if (myAppList != null && myAppList.isNotEmpty) {
        for (var element in myAppList) {
          AppFrontData app = AppFrontData.fromJson(element);
          if (app.nativeEnum != null && app.nativeEnum?.name != null) {
            app.name = app.nativeEnum!.name; // 多语言问题
          }
          newList.add(app);
        }
      }
    }
    // 默认展现应用
    if (newList.isEmpty) {
      AppFrontData task = AppFrontData(
          name: O2NativeAppEnum.task.name,
          key: O2NativeAppEnum.task.key,
          type: O2AppTypeEnum.native,
          nativeEnum: O2NativeAppEnum.task);
      newList.add(task);
      AppFrontData taskcompleted = AppFrontData(
          name: O2NativeAppEnum.taskcompleted.name,
          key: O2NativeAppEnum.taskcompleted.key,
          type: O2AppTypeEnum.native,
          nativeEnum: O2NativeAppEnum.taskcompleted);
      newList.add(taskcompleted);
      AppFrontData read = AppFrontData(
          name: O2NativeAppEnum.read.name,
          key: O2NativeAppEnum.read.key,
          type: O2AppTypeEnum.native,
          nativeEnum: O2NativeAppEnum.read);
      newList.add(read);
      AppFrontData readcompleted = AppFrontData(
          name: O2NativeAppEnum.readcompleted.name,
          key: O2NativeAppEnum.readcompleted.key,
          type: O2AppTypeEnum.native,
          nativeEnum: O2NativeAppEnum.readcompleted);
      newList.add(readcompleted);
    }
    state.myAppList.addAll(newList);
    _loadWorkNumbers();
  }


  /// 待办 待阅等数量查询
  Future<void> _loadWorkNumbers() async {
    final person = O2ApiManager.instance.o2User?.distinguishedName ?? '';
    if (person.isEmpty) {
      return;
    }
    final workCount =
        await ProcessSurfaceService.to.workCountWithPerson(person);
    if (workCount != null) {
      final list = state.myAppList.toList();
      for (var element in list) {
        if (element != null && element.type == O2AppTypeEnum.native) {
          switch (element.nativeEnum) {
            case O2NativeAppEnum.task:
              element.showNumber = workCount.task ?? 0;
              break;
            // case O2NativeAppEnum.taskcompleted:
            //   element.showNumber = workCount.taskCompleted ?? 0;
            //   break;
            case O2NativeAppEnum.read:
              element.showNumber = workCount.read ?? 0;
              break;
            // case O2NativeAppEnum.readcompleted:
            //   element.showNumber = workCount.readCompleted ?? 0;
            //   break;
            default:
              break;
          }
        }
      }
      state.myAppList.clear();
      state.myAppList.addAll(list);
    }
  }
 

  void openApp(AppFrontData? data) {
    if (data != null) {
      if (data.type == O2AppTypeEnum.native) {
        if (data.flutterPath != null) {
          if (O2OARoutes.appAttendance == data.flutterPath || O2OARoutes.appAttendanceOld == data.flutterPath) {
            FastCheckInService.instance.stop();
          }
          var routerPath = data.flutterPath!;
          if (data.displayName?.trim().isNotEmpty == true) {
            if (routerPath.contains('?')) {
              routerPath += '&displayName=${data.displayName}';
            } else {
              routerPath += '?displayName=${data.displayName}';
            }
          }
          Get.toNamed(routerPath);
        }
      } else if (data.type == O2AppTypeEnum.portal) {
        if (data.portalId != null) {
          PortalPage.open(data.portalId!, title: data.name ?? '');
        }
      }
    }
  }

  Future<void> openMoreApps() async {
    await Get.toNamed(O2OARoutes.homeApps);
    loadMyAppList();
  }

  void openHotPic(HotpicData data) {
    if (data.isBBSInfo()) {
      BbsSubjectPage.open(data.infoId!, title: data.title ?? '');
    } else if (data.isCmsInfo()) {
      CmsDocumentPage.open(data.infoId!, title: data.title ?? '');
    }
  }

  ///
  /// 点击扫一扫
  ///
  void clickScan() {
    ScanPage.o2ScanBiz();
  }

  ///
  /// 点击搜索
  ///
  void clickSearch() {
    Get.toNamed(O2OARoutes.homeSearch);
  }

  /// 启动水印
  void checkEnbaleWaterMark() {
    if (ProgramCenterService.to.waterMarkEnable()) {
      _eventBus.emit(EventBus.globalWaterMarkEnableMsg);
    }
  }

  ///
  /// 点击新建工作
  ///
  Future<void> clickAddWork() async {
    // 选择启动流程
    var result = await ProcessPickerPage.startPicker(ProcessPickerMode.process);
    if (result != null && result is ProcessData) {
      CreateFormPage.startProcess(true, process: result);
    }
  }

  ///
  /// 切换列表类型
  ///
  void clickChangeListType(int type) {
    if (type == state.listType){
      return ;
    }
    state.listType = type;
    refreshDataList();
  }

  Future<void> tapTask(TaskData task) async {
    if (task.work != null && task.work?.isNotEmpty == true) {
      await ProcessWebviewPage.open(task.work!,
          title: task.title ??
              'process_work_no_title'.trArgs(['${task.processName}']));
      // 刷新列表
      // refreshDataList(); // 已经有 eventbus
    }
  }

  Future<void> tapDocument(DocumentData document) async {
    OLogger.d("点击了文档：${document.title}");
    await CmsDocumentPage.open(document.id!, title: document.title ?? '');
    // 刷新列表
    // refreshDataList(); // 已经有 eventbus
  }
}
